/**
 * StringToLocalDateTimeConverter.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年1月18日
 */
package com.pshare.util.time;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * 字符串转LocalDateTime转换器
 * 
 */
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {

	@Override
	public LocalDateTime convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}

		source = source.trim();
		if (!org.springframework.util.StringUtils.hasText(source)) {
			return null;
		}

		int year = 0, month = 0, day = 0;
		int hour = 0, minute = 0, second = 0;
		String[] dts = source.split(" ");
		String ds = dts[0];
		String ts = dts[1];
		int dsLength = ds.length();
		if (NumberUtils.isNumber(ds)) {
			if (dsLength == 6 || dsLength == 7) {
				year = Integer.parseInt(ds.substring(0, 4));
				month = Integer.parseInt(ds.substring(4, 5));
				day = Integer.parseInt(ds.substring(5));
			} else if (dsLength == 8) {
				year = Integer.parseInt(ds.substring(0, 4));
				month = Integer.parseInt(ds.substring(4, 6));
				day = Integer.parseInt(ds.substring(6));
			}
		} else {
			String[] ss = null;
			if (ds.indexOf("-") > 0) {
				ss = ds.split("\\-");
			} else if (ds.indexOf(".") > 0) {
				ss = ds.split("\\.");
			} else {
				throw new IllegalArgumentException("failed to parse LocalDate " + source);
			}
			year = Integer.parseInt(ss[0]);
			month = Integer.parseInt(ss[1]);
			day = Integer.parseInt(ss[2]);
		}
		
		int tsLength = ts.length();
		if (tsLength == 2) {
			hour = Integer.parseInt(ts);
		} else if (tsLength == 5 && ts.indexOf(":") == 2) {
			String[] ss = ts.split("\\:");
			hour = Integer.parseInt(ss[0]);
			minute = Integer.parseInt(ss[1]);
		} else if (tsLength == 8 && ts.indexOf(":") == 2 && ts.lastIndexOf(":") == 5) {
			String[] ss = ts.split("\\:");
			hour = Integer.parseInt(ss[0]);
			minute = Integer.parseInt(ss[1]);
			second = Integer.parseInt(ts.substring(6));
		}
		if (hour == 0) {
			throw new IllegalArgumentException("failed to parse LocalTime " + source);
		}

		LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute, second);
		return dateTime;
	}

	public static final DateFormat DF_SHORT = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
	public static final DateFormat DF_LINE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final DateFormat DF_POINT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

}
